package com.ruoyi.business.controller;

import com.ruoyi.business.domain.ClassInfo;
import com.ruoyi.business.domain.dto.*;
import com.ruoyi.business.domain.enums.ProjectTypeEnum;
import com.ruoyi.business.domain.vo.FrontLineChartVO;
import com.ruoyi.business.domain.vo.FrontNewScoreVO;
import com.ruoyi.business.domain.vo.FrontPieChartVO;
import com.ruoyi.business.domain.vo.FrontShortRunVO;
import com.ruoyi.business.service.IClassInfoService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.Score;
import com.ruoyi.business.service.IScoreService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 成绩Controller
 * 
 * @author lcz
 * @date 2025-02-23
 */
@Api(tags = "成绩相关接口")
@RestController
@RequestMapping("/business/score")
public class ScoreController extends BaseController
{
    @Autowired
    private IScoreService scoreService;

    @Autowired
    private IClassInfoService classInfoService;

    /**
     * 查询成绩列表
     */
    @ApiIgnore
//    @PreAuthorize("@ss.hasPermi('business:score:list')")
    @GetMapping("/list")
    public TableDataInfo list(Score score)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long roleId = sysUser.getRoles().get(0).getRoleId();
        if (roleId.toString().equals("110")){
            score.setSchoolId(sysUser.getSchoolId());
        }
        if (roleId.toString().equals("120")){
            ClassInfo param = new ClassInfo();
            param.setTeacherId(sysUser.getUserId());
            List<ClassInfo> classInfoList = classInfoService.selectClassInfoList(param);
            List<Long> classIdList = classInfoList.stream().map(ClassInfo::getId).collect(Collectors.toList());
            score.setClassIdList(classIdList);
        }
        startPage();
        List<Score> list = scoreService.selectScoreList(score);
        return getDataTable(list);
    }

    /**
     * 导出成绩列表
     */
    @ApiIgnore
//    @PreAuthorize("@ss.hasPermi('business:score:export')")
    @Log(title = "成绩", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Score score)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long roleId = sysUser.getRoles().get(0).getRoleId();
        if (roleId.toString().equals("110")){
            score.setSchoolId(sysUser.getSchoolId());
        }
        if (roleId.toString().equals("120")){
            ClassInfo param = new ClassInfo();
            param.setTeacherId(sysUser.getUserId());
            List<ClassInfo> classInfoList = classInfoService.selectClassInfoList(param);
            List<Long> classIdList = classInfoList.stream().map(ClassInfo::getId).collect(Collectors.toList());
            score.setClassIdList(classIdList);
        }
        List<Score> list = scoreService.selectScoreList(score);
        ExcelUtil<Score> util = new ExcelUtil<Score>(Score.class);
        util.exportExcel(response, list, "成绩数据");
    }

    /**
     * 获取成绩详细信息
     */
    @ApiIgnore
//    @PreAuthorize("@ss.hasPermi('business:score:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(scoreService.selectScoreById(id));
    }

    /**
     * 新增成绩
     */
    @ApiIgnore
//    @PreAuthorize("@ss.hasPermi('business:score:add')")
    @Log(title = "成绩", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Score score)
    {
        return toAjax(scoreService.insertScore(score));
    }

    /**
     * 修改成绩
     */
    @ApiIgnore
//    @PreAuthorize("@ss.hasPermi('business:score:edit')")
    @Log(title = "成绩", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Score score)
    {
        return toAjax(scoreService.updateScore(score));
    }

    /**
     * 删除成绩
     */
    @ApiIgnore
//    @PreAuthorize("@ss.hasPermi('business:score:remove')")
    @Log(title = "成绩", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(scoreService.deleteScoreByIds(ids));
    }

    /** 前端接口 ***************************************************************************************************/
    /** 前端接口 ***************************************************************************************************/
    /** 前端接口 ***************************************************************************************************/

    /**
     * 查询单项成绩列表
     * 接口路径：/score/front/list
     */
    @GetMapping("/front/singleList")
    @ApiOperation("查询单项成绩列表")
    public TableDataInfo<Score> frontSingleList(@Validated FrontSingleListDTO dto)
    {
        Score score = new Score();
        Long studentId = 0l;
        if (ObjectUtils.isEmpty(dto.getStudentId())) {
            studentId = SecurityUtils.getLoginUser().getUser().getUserId();
        }else {
            studentId = dto.getStudentId();
        }
        score.setStudentId(studentId);
        score.setProjectType(dto.getProjectType());
        startPage();
        List<Score> list = scoreService.selectScoreList(score);
        return getDataTable(list);
    }

    /**
     * 查询某测验的单项成绩列表
     * 接口路径：/score/front/list
     */
    @GetMapping("/front/listByTestSession")
    @ApiOperation("查询某测验的单项成绩列表")
    public TableDataInfo<Score> frontListByTestSession(@Validated FrontListByTestSessionDTO dto)
    {
        startPage();
        List<Score> list = scoreService.frontListByTestSession(dto);
        return getDataTable(list);
    }
//
//    /**
//     * 获取成绩详细信息
//     * 接口路径：/score/front/info
//     */
//    @ApiOperation("前台获取成绩详细信息")
//    @GetMapping(value = "/front/info")
//    public R<Score> frontInfo(@RequestParam("id") Long id)
//    {
//        return R.ok(scoreService.selectScoreById(id));
//    }
//
//    /**
//     * 新增成绩
//     * 接口路径：/score/front/add
//     */
//    @ApiOperation("前台新增成绩")
//    @PostMapping("/front/add")
//    public AjaxResult frontAdd(@RequestBody Score score)
//    {
//        return toAjax(scoreService.insertScore(score));
//    }
//
//    /**
//     * 修改成绩
//     * 接口路径：/score/front/edit
//     */
//    @ApiOperation("前台修改成绩")
//    @PostMapping("/front/edit")
//    public AjaxResult frontEdit(@RequestBody Score score)
//    {
//        return toAjax(scoreService.updateScore(score));
//    }
//
//    /**
//     * 删除成绩
//     * 接口路径：/score/front/delete
//     */
//    @ApiOperation("前台删除成绩")
//    @GetMapping("/front/delete")
//    public AjaxResult frontRemove(@RequestParam Long[] ids)
//    {
//        return toAjax(scoreService.deleteScoreByIds(ids));
//    }
    /**
     * 查询用户所有项目最新成绩（首页成绩）
     */
    @ApiOperation("查询用户所有项目最新成绩（首页成绩）")
    @PostMapping("/front/newScore")
    public R<FrontNewScoreVO> frontNewScore(@RequestBody FrontNewScoreDTO dto){
        return scoreService.frontNewScore(dto);
    }

    /**
     * 查询学生单项成绩折线图
     */
    @ApiOperation("查询学生单项成绩折线图")
    @PostMapping("/front/lineChart")
    public R<FrontLineChartVO> frontLineChart(@Validated @RequestBody FrontLineChartDTO dto){
        return scoreService.frontLineChart(dto);
    }

    /**
     * 查询班级单项成绩折线图
     */
    @ApiOperation("查询班级单项成绩折线图")
    @PostMapping("/front/lineChartByClassId")
    public R<FrontLineChartVO> frontLineChartByClassId(@Validated @RequestBody FrontLineChartByClassIdDTO dto){
        return scoreService.frontLineChartByClassId(dto);
    }

    /**
     * 查询某测验单项成绩饼图
     */
    @ApiOperation("查询某测验单项成绩饼图")
    @GetMapping("/front/pieChart")
    public R<List<FrontPieChartVO>> frontPieChart(@RequestParam("testSessionId") Long testSessionId,
                                                  @RequestParam("classId") Long classId,
                                            @RequestParam("projectType") String projectType){
        return scoreService.frontPieChart(testSessionId, projectType, classId);
    }

    /**
     * 短跑项目列表
     */
    @ApiOperation("短跑项目列表")
    @GetMapping("/front/shortRunList")
    public R<List<FrontShortRunVO>> frontShortRunList(){
        List<FrontShortRunVO> list = new ArrayList<>();
        // TODO: 遍历项目类型枚举类，将code>=9的元素添加到list中
        for (ProjectTypeEnum projectTypeEnum : ProjectTypeEnum.values()) {
            Integer code = Integer.parseInt(projectTypeEnum.getCode());
            if (code >= 9) {
                FrontShortRunVO vo = new FrontShortRunVO();
                vo.setId(code.longValue());
                vo.setProjectName(projectTypeEnum.getValue());
                list.add(vo);
            }
        }
        return R.ok(list);
    }
}
